import { NextRequest } from 'next/server';
import { withMiddleware } from '@/lib/middleware/entry';
import { prisma } from '@/lib/prisma';
import { authenticateRequest } from '@/utils/auth';
import { errorResponse, successResponse } from '@/lib/response';
import { UserRole } from '@/constants/user';

async function handler(req: NextRequest) {
    const authResult = await authenticateRequest(req, UserRole.NORMAL_USER);
    if (!authResult.success || !authResult.user) {
        return errorResponse(authResult.error || '身份验证失败');
    }
    const user = authResult.user;

    const favorites = await prisma.favorite.findMany({
        where: { userId: user.id },
        include: { 
            content: {
                include: {
                    categories: {
                        include: {
                            category: {
                                include: {
                                    menu: true
                                }
                            }
                        }
                    },
                    cover: true
                }
            } 
        },
        orderBy: { createdAt: 'desc' },
    });

    // 获取所有唯一的菜单
    const menuMap = new Map();
    
    favorites.forEach(favorite => {
        favorite.content.categories.forEach(contentCategory => {
            const menu = contentCategory.category.menu;
            if (!menuMap.has(menu.id)) {
                menuMap.set(menu.id, {
                    id: menu.id,
                    name: menu.name,
                    icon: menu.icon,
                    path: menu.path,
                    contents: []
                });
            }
            
            // 将收藏内容添加到对应菜单下
            const menuData = menuMap.get(menu.id);
            const existingContent = menuData.contents.find((c: any) => c.id === favorite.content.id);
            if (!existingContent) {
                menuData.contents.push({
                    ...favorite,
                    id: favorite.content.id,
                    content: {
                        ...favorite.content,
                        cover: favorite.content.cover?.url || null
                    }
                });
            }
        });
    });

    // 转换为数组并添加"全部"选项
    const menuList = Array.from(menuMap.values());
    
    const result = {
        menus: [
            {
                id: 'all',
                name: '全部',
                icon: null,
                path: '',
                contents: favorites.map(favorite => ({
                    ...favorite,
                    id: favorite.content.id,
                    content: {
                        ...favorite.content,
                        cover: favorite.content.cover?.url || null
                    }
                }))
            },
            ...menuList
        ],
        total: favorites.length
    };

    return successResponse(result);
}

export const POST = withMiddleware(handler as any);